package encaps.action;

import encaps.entities.Grant;
import encaps.entities.Person;
import encaps.entities.PersonLocal;
import encaps.entities.PersonLocalHome;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Labels;
import encaps.utils.EntityUtil;
import encaps.utils.SystemException;
import encaps.utils.XMLHelper;
import java.util.Date;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.naming.NamingException;
import org.jdom.Element;

public class DeletePersonAction extends Action {

    public static final String DELETE_PERSON = "deletePerson";
    protected ActionContext actionContext;
    private Long id;

    public DeletePersonAction(ActionContext context, Grant requiredGrant) {
        this.actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            PersonLocalHome personHome = EntityUtil.getPersonHome();
            id = Long.valueOf(actionContext.getTextParameter(ID));
            PersonLocal person = personHome.findByPrimaryKey(id);

            JMSUtil.sendLogMessage(Log.DELETE,
                    EntityUtil.getUserHome().findByLogin(actionContext.getUserLogin()).getID(),
                    actionContext.getUserLogin(), new Date(), Person.TABLE_NAME,
                    person.getId(), person.getName());
            person.remove();
            return XMLHelper.createTextMessage(Labels.getLabel(Labels.PERSON_DELETED_MESSAGE));
        } catch (RemoveException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.REMOVAL_ERROR_MESSAGE), ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_FIND_LOCAL_HOME_OBJECT_MESSAGE), ex);
        } catch (FinderException ex) {
            String message = String.format(Labels.getLabel(Labels.PERSON_NOT_FOUND_MESSAGE_PATTERN), id);
            throw new ActionExecutionException(message, ex);
        } catch (SystemException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        }

    }
}
